<?php
/**
 * 统计数据模型
 * @author ezhu <ezhu@jipukeji.com>
 */

namespace Shop\Model;

use Think\Model;

class StatModel extends Model{
    protected $tableName = 'store_order';
    
    /**
     * 获取商户的订单统计数据
     * @return array 统计数据
     */
    public function getOrderStatNum($store_id=0,$start_date = '', $end_date = ''){
        $return_data = array();
        $start_time = !empty($start_date) ? strtotime($start_date) : 0;
        $end_time = !empty($end_date) ? strtotime($end_date.' +1 day') : time();
        //订单总数
        $order_where['status'] = array('egt', 1);
        //$order_where[] = 'FIND_IN_SET('.$store_id.', store_ids)';
        $order_where['store_ids'] = array('eq',$store_id); 
        $order_where[] = "`create_time`<{$end_time} AND `create_time`>$start_time";
        $return_data['order_count'] = M('StoreOrder')->where($order_where)->count();

        //待支付订单数量
        $add_where = array('o_status' => 0);
        $return_data['order_unpay_count'] = M('StoreOrder')->where($order_where)->where($add_where)->count();
        //交易成功
        $add_where = array('o_status' => 202);
        $return_data['order_success_count'] = M('StoreOrder')->where($order_where)->where($add_where)->count();
        //退款
        $add_where = array('o_status' => array('IN', '300,301,302,303'));
        $return_data['order_refund_count'] = M('StoreOrder')->where($order_where)->where($add_where)->count();
        //已支付
        $add_where = array('payment_time' => array('gt', 0));
        $return_data['order_ispay_count'] = M('StoreOrder')->where($order_where)->where($add_where)->count();
    
        //已取消订单
        //$add_where = array('order_status'=>-1);
        //$return_data['order_cancel_count'] = M('Order')->where($order_where)->where($add_where)->count();
        //已成交金额
        $shop = $this->field('sum(total_amount) amount')->where('o_status=202')->where($order_where)->find();
        $return_data['finish_amount'] = $shop['amount'];
    
        return $return_data;
    }
    
    /**
     * 获取订单图表所需数据
     * @param int $store_id 商户id
     * @param date $start_date 开始日期
     * @param date $end_date 结束日期
     * @param string $return_type 返回类型
     * @return array 组装好的json数据
     */
    public function getOrderChartData($store_id=0 ,$start_date = '', $end_date = '', $return_type = 'chat'){
        $return_data = $return_array = array();
        //起始时间处理
        $todayStart = strtotime(date('Y-m-d'));
        $start_time = !empty($start_date) ? strtotime($start_date) : $todayStart - 30 * 86400;
        $end_time = !empty($end_date) ? strtotime($end_date) : $todayStart;
        $end_time += 86400;
        if($start_time >= $end_time){
            $return_data['error'] = '非正常时间段';
            return $return_data;
        }
        if(empty($store_id)){
            $return_data['error'] = '参数错误！';
            return $return_data;
        }
        //日期模板
        $data_tpl = array();
        for($i = $start_time; $i < $end_time; $i+=86400){
            $data_tpl[date('m-d', $i)] = 0;
            $return_array[date('Y-m-d', $i)] = array('create' => 0, 'payment' => 0, 'total_amount' => 0);
        }
        $order_where = array('status' => 1);
        $typearr = array(
                'create' => '下单笔数',
                'payment' => '支付笔数',
        );
        $return_data['legend'] = json_encode(array_values($typearr));
        $return_data['xAxis'] = json_encode(array_keys($data_tpl));
        foreach($typearr as $type => $desc){
            //按下单时间、支付时间
            $add_where = array(
                    "`{$type}_time` < {$end_time}",
                    "`{$type}_time` > {$start_time}"
            );
            // 店铺商户
            //$add_where[] = 'find_in_set('.$store_id.', store_ids)';
            $add_where['store_ids'] = array('eq',$store_id);
            $list = M('Order')->field("id,{$type}_time,total_amount")->where($add_where)->where($order_where)->select();
            $box = $data_tpl;
            foreach($list as $line){
                $box[date('m-d', $line["{$type}_time"])] ++;
                $return_array[date('Y-m-d', $line["{$type}_time"])][$type] ++;
                if($type == 'payment'){
                    $return_array[date('Y-m-d', $line["{$type}_time"])]['total_amount'] += $line['total_amount'];
                }
            }
    
            $return_data['data'][] = array(
                    'name' => $desc,
                    'type' => 'line',
                    //'stack' => '总量',
                    'data' => array_values($box)
            );
        }
        $return_data['data'] = json_encode($return_data['data']);
        //返回组装好的数据
        return $return_type == 'chat' ? $return_data : $return_array;
    }
    
    /**
     * 商品销量
     * @author Justin
     */
    function getItemStat($store_id=0,$start_date = '', $end_date = ''){
        $return_data = array();
        $start_time = !empty($start_date) ? strtotime($start_date) : 0;
        $end_time = !empty($end_date) ? strtotime($end_date.' +1 day') : strtotime(date("Y-m-d", strtotime('+1 day')));
        //获取订单
        $where = array(
                'o_status' => array('IN', '200, 201, 202'),
                'create_time' => array('between', array($start_time, $end_time))
        );
        $where[] = 'FIND_IN_SET('.$store_id.', store_ids)';
        $item_id = I('get.item_id', 0, intval);
        if($item_id > 0){
            $where[] = 'FIND_IN_SET('.$item_id.', item_ids)';
        }
    
        $lists_order = M('Order')->field('id')->where($where)->cache(true, 86400)->select();
    
        //获取商品销量
        foreach($lists_order as $v){
            $oMap['store_id'] = $store_id;
            $oMap['order_id'] = $v['id'];
            $lists_order_item = M('OrderItem')->field('item_id, quantity')->where($oMap)->cache(true, 86400)->select();
            foreach($lists_order_item as $value){
                if(isset($return_data[$value['item_id']])){
                    $return_data[$value['item_id']] += $value['quantity'];
                }else{
                    $return_data[$value['item_id']] = $value['quantity'];
                }
            }
        }
        if($item_id > 0){
            $return_data = array($item_id => $return_data[$item_id]?:0);
        }
        return $return_data;
    }


    
    
    /**
     * 商品销量明细列表
     */
    public function itemRecordList($start_date, $end_date, $item_id = 0,$store_id=0){
        $start_time = !empty($start_date) ? strtotime($start_date) : 0;
        $end_time = !empty($end_date) ? strtotime($end_date.' +1 day') : strtotime(date("Y-m-d", strtotime('+1 day')));
        //获取订单
        $where = array(
                'o_status' => array('IN', '200, 201, 202'),
                'status' => 1,
                'create_time' => array('between', array($start_time, $end_time))
        );
        if($item_id > 0){
            $where[] = 'FIND_IN_SET('.$item_id.', item_ids)';
        }else{
            return [];
        }
        $where[] = 'FIND_IN_SET('.$store_id.', store_ids)';
        $lists_order = A('Home/Page', 'Event')->lists('Order', $where, 'id desc', 15, null, 'id, uid, payment_id, order_sn, create_time');
        foreach($lists_order as &$v){
            $map = array(
                    'order_id' => $v['id'],
                    'item_id' => $item_id,
                    'store_id' => $store_id
            );
            $v['number'] = M('OrderItem')->where($map)->sum('quantity');
            $v['ship'] = M('OrderShip')->field('ship_uname,ship_mobile')->where(array('payment_id' => $v['payment_id']))->find();
        }
        return $lists_order;
    }

    
}
